<?php

namespace common\domain\components\filters;

use common\domain\components\AccessToken;
use yii\filters\auth\AuthMethod;
use yii\web\UnauthorizedHttpException;

/**
 * Class ApiAuth.
 */
class ApiAuth extends AuthMethod
{
    public function authenticate($user, $request, $response): ?\yii\web\IdentityInterface
    {
        $access_token = AccessToken::getRequestAccessToken();
        if (is_string($access_token)) {
            $identity = $user->loginByAccessToken($access_token, static::class);
            if (null !== $identity) {
                return $identity;
            }
        }

        $this->handleFailure($response);

        return null;
    }

    public function handleFailure($response)
    {
        throw new UnauthorizedHttpException('Unauthorized', 1001);
    }
}
